package com.xy.interceptor;

import com.xy.model.AdminUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public class MyHandlerInterceptor implements HandlerInterceptor {
		boolean checkWhiteURL(String url){
				if(url.equals("/wf-admin/login")){
						return true;
				}else if(url.equals("/wf-admin/index.html#/login?redirect=%2Findex")){
						return true;
				}else {
						return false;
				}
		}
		@Override
		public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
				log.info("MyHandlerInterceptor preHandle" + request.getRequestURI());
				HttpSession session = request.getSession();
				Object o = session.getAttribute("adminUser");
				AdminUser user = (AdminUser) o;
				if(checkWhiteURL(request.getRequestURI())){
						return true;
				}
				if (user == null) {
						response.setContentType("text/html;charset=UTF-8");
						response.sendRedirect("/wf-admin/login");
						return false;
				} else {
						if (session.getMaxInactiveInterval() < 60) {
								session.setMaxInactiveInterval(3 * 60);//session时间小于2/3，则刷新登录过期时间
						}
				}
				return true;
		}

		@Override
		public void postHandle(HttpServletRequest request, HttpServletResponse response, Object
			handler, ModelAndView modelAndView) throws Exception {

		}

		@Override
		public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object
			handler, Exception ex) throws Exception {

		}
}
